/*
 * author      : 吴中勤 
 * date        : 2018/9/15
 * description : data access service
 *               service -> das -> dao 可以做一些缓存服务
 *               service -> dao
 *               das层 和 dao层具有同样的接口
 */

package com.deepexi.adapter.converter.sap.sapdict;

import com.deepexi.adapter.common.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SapDictDAS {

    private static final Object cacheLock = new Object();
    private static final int CACHE_SIZE_FOR_DICT_TYPE = 20;

    @Autowired
    private SapDictMapper dict4MobyMapper;

    private Set<String> typeSet = new HashSet<>(CACHE_SIZE_FOR_DICT_TYPE);
    private static Map<String, List<SapDict>> cache = new HashMap<>(CACHE_SIZE_FOR_DICT_TYPE);

    public List<SapDict> listByType(String dictType) {
        if (StringUtil.isNullorEmpty(dictType))
            return null;
        queryDictByTypeAndCache(dictType);
        return cache.get(dictType);
    }

    /** 刷新缓存 */
    public void invalidate() {
        typeSet.clear();
        cache.clear();
    }

    /** 读取并缓存 */
    private void queryDictByTypeAndCache(String dictType) {
        if (!typeSet.contains(dictType)) {
            synchronized (SapDictDAS.cacheLock) {
                if (!typeSet.contains(dictType)) {
                    List<SapDict> dict4MobyList = dict4MobyMapper.listByDictType(dictType);
                    typeSet.add(dictType);
                    cache.put(dictType, dict4MobyList);
                }
            }
        }
    }
}
